package com.hjt.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.hjt.common.to.member.MemberAddressTo;
import com.hjt.common.utils.R;
import com.hjt.gulimall.ware.feign.MemberFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Random;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjt.common.utils.PageUtils;
import com.hjt.common.utils.Query;

import com.hjt.gulimall.ware.dao.WareInfoDao;
import com.hjt.gulimall.ware.entity.WareInfoEntity;
import com.hjt.gulimall.ware.service.WareInfoService;
import org.springframework.util.StringUtils;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {


    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 条件分页查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageWithCondition(Map<String, Object> params) {

        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        // 封装查询条件
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            wrapper.and(obj -> {
                obj.eq("id", key)
                    .or().like("name", key)
                    .or().like("address",key)
                    .or().like("areacode",key);
            });
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    // 根据地址计算运费
    @Override
    public BigDecimal getFare(Long addrId) {
        R info = memberFeignService.info(addrId);
        MemberAddressTo address = info.getData(new TypeReference<MemberAddressTo>() {});
        // TODO:根据地址计算运费
        return new BigDecimal(10);
    }
}